package com.ruoyi.wxmini.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.wxmini.bo.WxUserInfo;
import com.ruoyi.wxmini.domain.UserInfo;
import com.ruoyi.wxmini.entity.dto.UserLoginDTO;
import com.ruoyi.wxmini.service.IUserInfoService;
import com.ruoyi.wxmini.service.IWxMiniJwtService;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.time.Instant;

/**
 * 微信小程序登录接口
 *
 * @author weijiayu
 * @date 2025/4/25 22:15
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/wxmini")
public class WxLoginController {

    // 存储目录
    public static final String AVATAR_DIR = "D:/static/image/";
    private final WxMaService wxMaService;

    @Resource
    private IUserInfoService userInfoService;
    @Resource
    private IWxMiniJwtService jwtService;

    /**
     * 登陆接口
     */
    @SneakyThrows
    @ApiOperation("登录接口")
    @GetMapping("/login")
    public AjaxResult login(@ModelAttribute UserLoginDTO userLoginDTO) {
        System.out.println("用户登录：");
        if (StringUtils.isEmpty(userLoginDTO.getCode())) {
            return AjaxResult.error("empty jscode");
        }

        WxUserInfo wxUserInfo = new WxUserInfo();
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(userLoginDTO.getCode());
            // 同步微信侧用户信息：如果已注册，返回用户信息；如果未注册，自动注册并保存用户信息
            String openId = session.getOpenid();
            UserInfo userInfo = userInfoService.selectUserInfoByOpenId(openId);



            if (userInfo == null) {
                String avatarUrl =uploadAvatar(userLoginDTO.getAvatar());

                userInfo = new UserInfo();
                userInfo.setUserId(UUID.randomUUID().toString());
                userInfo.setOpenId(openId);
                userInfo.setUnionId(session.getUnionid());
                userInfo.setAvatarUrl(avatarUrl);
                userInfoService.insertUserInfo(userInfo);
            }
            // 只返回必要信息给前端
            wxUserInfo.wapper(session, userInfo);
            // 生成令牌，用于自定义业务接口鉴权
            wxUserInfo.setApiToken(jwtService.createToken(userInfo.getUserId()));
            return AjaxResult.success(wxUserInfo);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return AjaxResult.error();
        }
    }

    private String uploadAvatar(MultipartFile avatar) throws Exception {


        // 创建存储目录（如果不存在）
        File dir = new File(AVATAR_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //获取原始文件名
        String originalFilename = avatar.getOriginalFilename();


        // 提取文件扩展名
        int index = originalFilename.lastIndexOf(".");
        String ext = originalFilename.substring(index);
        // 生成随机 UUID 作为唯一标识
        String uid = java.util.UUID.randomUUID().toString();
        long timestamp = Instant.now().getEpochSecond();

        // 生成唯一文件名
        String fileName = String.format("avatar_%d_%s%s",timestamp,uid, ext);
        log.info("新文件名：{}",fileName);

        //新文件名存储在服务器的磁盘目录中
        String filePath= AVATAR_DIR+fileName;

        avatar.transferTo(new File(filePath));


        String pre="http://localhost:8080/image/";

        // 返回映射访问路径
        return pre + fileName;
    }

}
